#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from Src.Runner import RUNNER_EXCEL_PATH, EXCELS_PATH
from Src.OpenXL import ExcelDataOpt
from Utils.Timer import timer
import openpyxl
import os
import re


class ScriptData:
    def __init__(self):
        self.workbook = openpyxl.load_workbook(RUNNER_EXCEL_PATH)
        self.worksheet = self.workbook['Sheet1']
        self.func_mapping = None

    @timer()
    def get_excel_obj(self, row):
        file_name = self.worksheet.cell(row, 1).value
        file_path = os.path.join(EXCELS_PATH, file_name)
        return ExcelDataOpt(file_path)

    @timer()
    def get_func(self, row):
        obj = self.get_excel_obj(row)
        self.func_mapping = {
            "insert_data": obj.insert_data,
            "sr_specific_result": obj.sr_specific_result,
            "sr_title_nonadjacent": obj.sr_title_nonadjacent,
            "sr_between_range": obj.sr_between_range,
        }
        func_name = self.worksheet.cell(row, 2).value
        return self.func_mapping[func_name]

    def _parse_attrib_val(self, attrib_val):
        # 处理字符串
        if attrib_val.startswith("'") and attrib_val.endswith("'"):
            return attrib_val[1:-1]
        # 处理数字类型
        try:
            _attrib_val = int(attrib_val)
        except ValueError:
            pass
        else:
            return _attrib_val
        # 处理函数返回值
        func_name = re.match('^(<\d+>)([a-zA-Z_]+)$', attrib_val)
        if func_name:
            func_row_num = int(func_name.group(1).replace('<', '').replace('>', ''))
            return func_row_num, self.get_func(func_row_num)
        # 处理布尔值和None类型
        elif re.match('[tT][rR][uU][eE]', attrib_val):
            return True
        elif re.match('[fF][aA][lL][sS][eE]', attrib_val):
            return False
        elif re.match('[nN][oO][nN][eE]', attrib_val):
            return None
        # 处理元组类型
        elif attrib_val.startswith("(") and attrib_val.endswith(")"):
            return eval(attrib_val)
        # 处理列表类型
        elif attrib_val.startswith("[") and attrib_val.endswith("]"):
            return eval(attrib_val)
        # 处理字典类型
        elif attrib_val.startswith("{") and attrib_val.endswith("}"):
            return eval(attrib_val)
        else:
            raise ValueError('有尚未处理的属性[{0}]'.format(attrib_val))

    @timer()
    def get_func_attributes(self, row):
        attributes_dict = {}
        for col in range(4, self.worksheet.max_column + 1):
            _attribute = self.worksheet.cell(row, col).value
            if _attribute:
                attributes_dict[_attribute.split('=')[0]] = self._parse_attrib_val(_attribute.split('=')[1])
        return attributes_dict

    @timer()
    def get_return_row(self, row):
        return_row = self.worksheet.cell(row, 3).value
        func = self.get_func(row)
        attributes_dict = self.get_func_attributes(row)
        if return_row:
            result = func(**attributes_dict)
        else:
            func_row_num = attributes_dict['row'][0]
            _result = self.get_return_row(func_row_num)
            attributes_dict['row'] = _result['RowNum']
            result = func(**attributes_dict)
        return result

    @timer()
    def run_script(self, row):
        return self.get_return_row(row)


if __name__ == '__main__':
    data = ScriptData()
    data.run_script(5)
    # data.run_script(5)
